﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Joy.Erp.BasicArchives.ItemMasters;
using Joy.Erp.Ufida.Core;
using Microsoft.Extensions.Logging;

namespace Joy.Erp.Ufida.ItemMasters
{
    public class ItemMasterSyncAppService : UfidaAppService, IItemMasterSyncAppService
    {
        // 仓储
        protected IItemMasterRepository ItemMasterRepository => LazyServiceProvider.LazyGetRequiredService<IItemMasterRepository>();
        protected IItemCategoryRepository ItemCategoryRepository => LazyServiceProvider.LazyGetRequiredService<IItemCategoryRepository>();
        protected IUnitGroupRepository UnitGroupRepository => LazyServiceProvider.LazyGetRequiredService<IUnitGroupRepository>();

        // 应用服务
        protected IUnitGroupAppService UnitGroupAppService => LazyServiceProvider.LazyGetRequiredService<IUnitGroupAppService>();
        protected IItemMasterUfidaAppService ItemMasterUfidaAppService => LazyServiceProvider.LazyGetRequiredService<IItemMasterUfidaAppService>();

        public async Task<AnalysisDto> AnalyzeAsync()
        {
            var analysisDto = new AnalysisDto();
            analysisDto.Id = typeof(ItemMaster).FullName;

            // 获取U9数据的ID列表
            var u9list = await ItemMasterUfidaAppService.GetAllAsync();
            var u9Ids = u9list.Select(x => x.ID.ToString()).ToHashSet();
            analysisDto.U9Count = u9Ids.Count;

            // 使用数据库查询优化，只查询需要的字段
            var pmcQuery = await ItemMasterRepository.GetQueryableAsync();

            // 获取PMC总数
            analysisDto.Count = await AsyncExecuter.CountAsync(pmcQuery.Where(x => !x.IsDeleted));

            // 获取已同步的SourceKey列表
            var syncedSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x => !x.IsDeleted && x.SourceType == SourceConfig.SourceType)
                    .Select(x => x.SourceKey)
            );

            // 使用 HashSet 快速计算已同步数量
            analysisDto.AsyncCount = syncedSourceKeys.Count(key => u9Ids.Contains(key));
            analysisDto.UnasyncCount = analysisDto.U9Count - analysisDto.AsyncCount;
            analysisDto.SelfCount = analysisDto.Count - analysisDto.AsyncCount;

            return analysisDto;
        }

        public async Task<List<long>> GetUnasyncIds()
        {
            // 获取U9的所有ID
            var u9list = await ItemMasterUfidaAppService.GetAllAsync();
            var u9Ids = u9list.Select(x => x.ID).ToList();

            // 使用数据库查询，只查询已同步的SourceKey
            var pmcQuery = await ItemMasterRepository.GetQueryableAsync();
            var syncedSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x => !x.IsDeleted && x.SourceType == SourceConfig.SourceType)
                    .Select(x => x.SourceKey)
            );

            // 使用 HashSet 优化查找性能，时间复杂度从 O(n²) 降到 O(n)
            var syncedSourceKeySet = new HashSet<string>(syncedSourceKeys);

            // 找出未同步的ID
            var unasyncIds = u9Ids
                .Where(id => !syncedSourceKeySet.Contains(id.ToString()))
                .ToList();

            return unasyncIds;
        }

        public async Task<int> CreateByIds‌Async(long[] ids)
        {
            if (ids == null || ids.Length == 0) return 0;

            var successCount = 0;

            // 批量预查询已存在的记录，避免循环查询数据库
            var pmcQuery = await ItemMasterRepository.GetQueryableAsync();
            var idStrings = ids.Select(id => id.ToString()).ToList();
            var existingSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x =>
                        idStrings.Contains(x.SourceKey) && x.SourceType == SourceConfig.SourceType
                    )
                    .Select(x => x.SourceKey)
            );
            var existingSet = new HashSet<string>(existingSourceKeys);

            // 过滤出需要创建的ID
            var needCreateIds = ids.Where(id => !existingSet.Contains(id.ToString())).ToList();
            if (needCreateIds.Count == 0)
                return ids.Length;

            Logger.LogInformation(
                $"[批量同步-物料] 开始处理 {needCreateIds.Count} 条物料，总共 {ids.Length} 条（已存在 {existingSet.Count} 条）"
            );

            // 步骤1: 批量获取所有U9数据
            var allU9DataDict = new Dictionary<long, ItemMasterUfidaDto>();
            foreach (var id in needCreateIds)
            {
                try
                {
                    var itemMasterUfidaDto = await ItemMasterUfidaAppService.GetAsync(id);
                    if (itemMasterUfidaDto != null)
                    {
                        allU9DataDict[id] = itemMasterUfidaDto;
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-物料] 获取U9数据失败，Id: {id}");
                }
            }

            if (allU9DataDict.Count == 0)
                return existingSet.Count;

            // 步骤2: 批量预加载依赖数据
            var allCategoryIds = allU9DataDict.Values.Select(x => x.ItemCategoryID.ToString()).Distinct().ToList();
            var categoryCacheDict = await BatchLoadItemCategories(allCategoryIds);

            var allUnitGroupIds = allU9DataDict.Values.Select(x => x.UnitGroupID.ToString()).Distinct().ToList();
            var unitGroupCacheDict = await BatchLoadUnitGroups(allUnitGroupIds);

            // 步骤3: 创建所有实体对象
            var entities = new List<ItemMaster>();
            foreach (var kvp in allU9DataDict)
            {
                try
                {
                    var entity = GetEntity(kvp.Value, categoryCacheDict, unitGroupCacheDict);
                    if (entity != null)
                        entities.Add(entity);
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-物料] 创建实体失败，Id: {kvp.Key}");
                }
            }

            // 步骤4: 批量插入
            if (entities.Count > 0)
            {
                using (var uow = UnitOfWorkManager.Begin(new Volo.Abp.Uow.AbpUnitOfWorkOptions(), requiresNew: true))
                {
                    try
                    {
                        await ItemMasterRepository.BulkInsertAsync(entities, autoSave: false);
                        await uow.CompleteAsync();
                        successCount = entities.Count;
                    }
                    catch (Exception ex)
                    {
                        Logger.LogWarning(ex, $"[批量同步-物料] 创建实体失败，{ex.Message}");
                    }
                }
            }

            Logger.LogInformation($"[批量同步-物料] 完成！成功创建 {successCount} 条，已存在 {existingSet.Count} 条，总计 {successCount + existingSet.Count} 条");

            return successCount + existingSet.Count;
        }

        public async Task<List<long>> GetSyncedIds()
        {
            var pmcQuery = await ItemMasterRepository.GetQueryableAsync();
            var syncedSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x => !x.IsDeleted && x.SourceType == SourceConfig.SourceType)
                    .Select(x => x.SourceKey)
            );
            return syncedSourceKeys
                .Select(
                    key => long.TryParse(key, out var parsedId) ? (long?)parsedId : null
                )
                .Where(id => id.HasValue)
                .Select(id => id.Value)
                .ToList();
        }

        public async Task<int> UpdateByIdsAsync(long[] ids)
        {
            if (ids == null || ids.Length == 0) return 0;

            Logger.LogInformation($"[批量同步-物料] 开始处理 {ids.Length} 条更新");
            var pmcQuery = await ItemMasterRepository.GetQueryableAsync();
            var idStrings = ids.Select(id => id.ToString()).ToList();
            var existingEntities = await AsyncExecuter.ToListAsync(
                pmcQuery.Where(x =>
                    idStrings.Contains(x.SourceKey) && x.SourceType == SourceConfig.SourceType
                )
            );
            if (existingEntities.Count == 0)
            {
                Logger.LogWarning($"[批量同步-物料] 没有找到需要更新或删除的记录");
                return 0;
            }
            var entityDict = existingEntities.ToDictionary(x => x.SourceKey, x => x);

            var allU9DataDict = new Dictionary<long, ItemMasterUfidaDto>();
            foreach (var id in ids)
            {
                if (!entityDict.ContainsKey(id.ToString()))
                    continue;

                try
                {
                    var dto = await ItemMasterUfidaAppService.GetAsync(id);
                    if (dto != null)
                        allU9DataDict[id] = dto;
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-物料] 获取U9数据失败，Id: {id}");
                }
            }

            var allCategoryIds = allU9DataDict.Values.Select(x => x.ItemCategoryID.ToString()).Distinct().ToList();
            var categoryCacheDict = await BatchLoadItemCategories(allCategoryIds);

            var allUnitGroupIds = allU9DataDict.Values.Select(x => x.UnitGroupID.ToString()).Distinct().ToList();
            var unitGroupCacheDict = await BatchLoadUnitGroups(allUnitGroupIds);

            var entitiesToUpdate = new List<ItemMaster>();
            var entitiesToDelete = new List<ItemMaster>();
            foreach (var id in ids)
            {
                try
                {
                    var key = id.ToString();
                    if (!entityDict.TryGetValue(key, out var entity))
                        continue;

                    if (!allU9DataDict.TryGetValue(id, out var u9Data))
                    {
                        entitiesToDelete.Add(entity);
                        continue;
                    }

                    if (!categoryCacheDict.TryGetValue(u9Data.ItemCategoryID.ToString(), out var categoryDto))
                    {
                        Logger.LogWarning($"[批量同步-物料] 未找到物料分类，SourceKey: {u9Data.ItemCategoryID}");
                        continue;
                    }

                    if (!unitGroupCacheDict.TryGetValue(u9Data.UnitGroupID.ToString(), out var unitGroupDto))
                    {
                        Logger.LogWarning($"[批量同步-物料] 未找到单位组，SourceKey: {u9Data.UnitGroupID}");
                        continue;
                    }

                    entity.ItemCategoryId = categoryDto.Id;
                    entity.Code = u9Data.Code;
                    entity.Name = u9Data.Name;
                    entity.Spec = u9Data.SPECS;
                    entity.UnitGroupId = unitGroupDto.Id;
                    entity.CanBePurchased = u9Data.IsPurchaseEnable;
                    entity.Sellable = u9Data.IsSalesEnable;
                    entity.CanBeProduced = u9Data.IsBuildEnable;
                    entity.CanBeOutsourced = u9Data.IsOutsideOperationEnable;
                    entity.ItemFormAttribute = u9Data.ItemFormAttribute;
                    entity.Enabled = u9Data.IsEffective;
                    entity.SourceCreatedOn = u9Data.CreatedOn;
                    entitiesToUpdate.Add(entity);
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-物料] 修改实体失败，Id: {id}");
                }
            }

            if (entitiesToUpdate.Count == 0 && entitiesToDelete.Count == 0)
            {
                Logger.LogInformation($"[批量同步-物料] 无需更新或删除记录");
                return 0;
            }

            var updateCount = 0;
            var deleteCount = 0;
            using (var uow = UnitOfWorkManager.Begin(new Volo.Abp.Uow.AbpUnitOfWorkOptions(), requiresNew: true))
            {
                try
                {
                    if (entitiesToUpdate.Count > 0)
                    {
                        await ItemMasterRepository.BulkUpdateAsync(
                            entitiesToUpdate,
                            autoSave: false
                        );
                        updateCount = entitiesToUpdate.Count;
                    }

                    if (entitiesToDelete.Count > 0)
                    {
                        await ItemMasterRepository.BulkDeleteAsync(
                            entitiesToDelete,
                            autoSave: false
                        );
                        deleteCount = entitiesToDelete.Count;
                    }

                    await uow.CompleteAsync();
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-物料] 批量更新/删除失败，{ex.Message}");
                }
            }
            Logger.LogInformation($"[批量同步-物料] 完成！成功更新 {updateCount} 条，删除 {deleteCount} 条");
            return updateCount + deleteCount;
        }

        private async Task<Dictionary<string, ItemCategoryDto>> BatchLoadItemCategories(List<string> sourceKeys)
        {
            if (sourceKeys == null || sourceKeys.Count == 0) return new Dictionary<string, ItemCategoryDto>();

            var query = await ItemCategoryRepository.GetQueryableAsync();
            var items = await AsyncExecuter.ToListAsync(
                query.Where(x =>
                    sourceKeys.Contains(x.SourceKey) && x.SourceType == SourceConfig.SourceType
                )
            );

            return items.ToDictionary(
                x => x.SourceKey,
                x => ObjectMapper.Map<ItemCategory, ItemCategoryDto>(x)
            );
        }

        private async Task<Dictionary<string, UnitGroupDto>> BatchLoadUnitGroups(List<string> sourceKeys)
        {
            if (sourceKeys == null || sourceKeys.Count == 0) return new Dictionary<string, UnitGroupDto>();

            var query = await UnitGroupRepository.GetQueryableAsync();
            var items = await AsyncExecuter.ToListAsync(
                query.Where(x =>
                    sourceKeys.Contains(x.SourceKey) && x.SourceType == SourceConfig.SourceType
                )
            );

            return items.ToDictionary(
                x => x.SourceKey,
                x => ObjectMapper.Map<UnitGroup, UnitGroupDto>(x)
            );
        }

        private ItemMaster GetEntity(
            ItemMasterUfidaDto itemMasterUfidaDto,
            Dictionary<string, ItemCategoryDto> categoryCacheDict,
            Dictionary<string, UnitGroupDto> unitGroupCacheDict
        )
        {
            // 从缓存获取 ItemCategory
            if (!categoryCacheDict.TryGetValue(itemMasterUfidaDto.ItemCategoryID.ToString(), out var itemCategoryDto))
            {
                Logger.LogWarning($"未找到物料分类，SourceKey: {itemMasterUfidaDto.ItemCategoryID}");
                return null;
            }

            // 从缓存获取 UnitGroup
            if (!unitGroupCacheDict.TryGetValue(itemMasterUfidaDto.UnitGroupID.ToString(), out var unitGroupDto))
            {
                Logger.LogWarning($"未找到单位组，SourceKey: {itemMasterUfidaDto.UnitGroupID}");
                return null;
            }

            var entity = new ItemMaster
            {
                SourceType = SourceConfig.SourceType,
                SourceKey = itemMasterUfidaDto.ID.ToString(),
                SourceCreatedOn = itemMasterUfidaDto.CreatedOn,
                ItemCategoryId = itemCategoryDto.Id,
                Code = itemMasterUfidaDto.Code,
                Name = itemMasterUfidaDto.Name,
                Spec = itemMasterUfidaDto.SPECS,
                UnitGroupId = unitGroupDto.Id,
                CanBePurchased = itemMasterUfidaDto.IsPurchaseEnable,
                Sellable = itemMasterUfidaDto.IsSalesEnable,
                CanBeProduced = itemMasterUfidaDto.IsBuildEnable,
                CanBeOutsourced = itemMasterUfidaDto.IsOutsideOperationEnable,
                ItemFormAttribute = itemMasterUfidaDto.ItemFormAttribute,
                Enabled = itemMasterUfidaDto.IsEffective,

                // 手动设置审计字段
                CreationTime = Clock.Now,
                CreatorId = CurrentUser.Id,
                TenantId = CurrentTenant.Id,
            };

            entity.SetId(GuidGenerator.Create());
            return entity;
        }
    }
}
